const boom = require("boom");

const jwt = require("jsonwebtoken");
const secretKey = "shannnon";

const JWTToken = require("../models/token");

// 生成token
module.exports.generateToken = function (payload) {
  const token = jwt.sign(payload, secretKey, {
    expiresIn: "2h",
    // expiresIn: "15s",
  });
  return token;
};

// 验证token
module.exports.verifyToken = async function (token) {
  try {
    const decoded = jwt.verify(token, secretKey);
    return decoded;
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      await JWTToken.findOneAndDelete({ token });
      throw boom.unauthorized("Token expired");
    } else {
      await JWTToken.findOneAndDelete({ token });
      throw boom.unauthorized("Token expired");
    }
  }
};
